import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import folium
import squarify
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
from sklearn.cluster import KMeans

import os
print (os.listdir("Kaggle/ZomatoRestaurantData/input"))
pd.options.mode.chained_assignment = None

df_train = pd.read_csv('Kaggle/ZomatoRestaurantData/input/zomato.csv',encoding='latin-1')
df_train['rating_cat'] = df_train['Rating text'].map({"Not rated":-1,'Poor':0,'Average':2,'Good':3,'Very Good':4,'Excellent':5})
df_train.rename(columns = {'Aggregate rating':'rating_num', 'Has Table booking': 'Book', 'Has Online delivery': 'On_deliver', 'Is delivering now':'Cur_deliver',
                          'Switch to order menu' : 'Switch_menu', 'Average Cost for two' : 'Avg_cost_two', 'Price range' : 'Pr_range'}, inplace = True)
df_train.drop(['Rating color','Rating text'],axis=1,inplace=True)
print('Original Train Row: ',df_train.shape[0])
df_train = df_train.loc[df_train.rating_cat!=-1,:].copy()
print('Train Row: ',df_train.shape[0])

#######################################################################################################
#Y_Normal Distribution
rating = ['rating_num','rating_cat']
f,ax = plt.subplots(1,1,figsize=(12,4))
sns.countplot(df_train['rating_num'],color='green')
ax.tick_params('x',rotation=70)
ax.set_title('Y')
plt.show()


print('ID # / Name #')
df_train[['Restaurant ID','Restaurant Name']].apply(pd.Series.nunique,axis=0)

#######################################################################################################
#Most of the Data comes from India

with plt.style.context('bmh'):
    f = plt.figure(figsize=(9,9))
    ax = plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=2)
    cnt = df_train['Country Code'].value_counts().to_frame()
    squarify.plot(sizes=cnt.values,label=cnt.index,color=sns.color_palette('Paired',11),alpha=0.5,ax=ax)
    ax.set_title("TreeMap of India Country Code",fontsize=13)

    ax = plt.subplot2grid((3,3),(0,0))
    cnt = df_train['City'].value_counts().reset_index()
    cnt.rename(columns={'index':'City','City':'cnt'},inplace=True)
    sns.barplot(x='City',y='cnt',data=cnt.head(6),ax=ax)
    ax.tick_params(axis='x',rotation=70)
    ax.set_title("Top 6 City",size=12)
    ax.set_ylim([0,cnt['cnt'].head(1).values+500])
    for i, val in enumerate(cnt['cnt'].head(6)):
        ax.text(i,val+50,val,color='grey',ha='center')
    plt.show()

    ax = plt.subplot2grid((3,3),(2,1))
    cnt = df_train['Currency'].value_counts().reset_index()
    cnt.rename(columns={'index':'Currency','Currency':'cnt'},inplace=True)
    sns.barplot(x='Currency',y='cnt',data=cnt.head(6),color='b',ax=ax)
    ax.set_title('Top 6 Currency',size=12)
    ax.tick_params(axis='x',rotation=70)
    ax.set_ylim([0,8000])
    for i,val in enumerate(cnt['cnt'].head(2)):
        ax.text(i,val+50,val,color='grey',ha='center')
    sns.despine(left=True,bottom=True)
    plt.show()

print('City ',df_train['City'].nunique())
print('Currency ',df_train['Currency'].nunique())
print('Country Code ',df_train['Country Code'].nunique())

#######################################################################################################
# USA restaurant show
f = plt.figure(figsize=(12,8))
tr_USA = df_train.loc[df_train['Country Code']==216,['Latitude','Longitude']]
map_F = folium.Map(location=[35,-92],zoom_start=4)
for i,(lat,lon) in enumerate(tr_USA.values):
    folium.Marker([lat,lon]).add_to(map_F)
plt.show()

#######################################################################################################
# new delhi
df_test = df_train.loc[df_train.rating_cat==-1:].copy()
df_train = df_train.loc[df_train.rating_cat!=-1:].copy()

df_city = df_train.loc[(df_train['Country Code']==1) &(df_train['City']=='New Delhi'),:]
df_city.drop(['Country Code','City','Locality Verbose','Currency'],axis=1,inplace=True)
df_city = df_city.loc[df_city['Longitude']!=0,:]

tmp = df_city['rating_num'].map(np.round)
a = np.full(tmp.shape[0],False,dtype=bool)
print('Round')
((tmp-df_city['rating_cat']).map(np.round)).value_counts()
# check rating system
sys_check = df_city[['rating_num','rating_cat','Votes']].copy()
sys_check['distorted'] = (df_city['rating_num']-df_city['rating_cat']).map(np.round)
sys_check['diff'] = sys_check['rating_num']-sys_check['rating_cat']
g = sns.FacetGrid(data=sys_check,col='distorted')
g = g.map(plt.scatter,'diff','Votes',alpha=0.5)
plt.show()

#######################################################################################################
#Local K-Means:Where high restaurants gathered?
kmeans = KMeans(n_clusters=7,random_state=0).fit(df_city[['Longitude','Latitude']])
df_city['pos'] = kmeans.labels_
pop_local = df_city.groupby("pos")['Longitude','Latitude','rating_num'].agg({"Longitude":np.mean,'Latitude':np.mean,'rating_num':np.median}).reset_index()

with plt.style.context('bmh',after_reset=True):
    pal = sns.color_palette('Spectral',7)
    plt.figure(figsize=(8,6))
    for i in range(7):
        ix = df_city.pos == i
        plt.scatter(df_city.loc[ix,'Latitude'],df_city.loc[ix,'Longitude'],color=pal[i],label=str(i))
        plt.text(pop_local.loc[i,'Latitude'],pop_local.loc[ix,'Longitude'],str(i)+":"+str(pop_local.loc[i,'rating_num'].round(2)),fontsize=14,color='brown')
        plt.title('KMeans New Delhi Median Rating')
        plt.legend()
        plt.show()

votes_area = df_city.groupby("pos").agg({"Votes":[np.sum,np.mean]})
votes_area.columns = votes_area.droplevel(0)
votes_area.reset_index(inplace=True)
plt.figure(figsize=(8,4))
ax = plt.subplot(1,2,1)
sns.barplot(x='pos',y='sum',data=votes_area,palette=sns.cubehelix_palette(n_colors=7,start=2.4,rot=.1),ax=ax)
ax.set_title("Summation Votes")

ax = plt.subplot(1,2,2)
sns.barplot(x='pos',y='mean',data=votes_area,palette=sns.cubehelix_palette(n_colors=7,start=3,rot=.1),ax=ax)
ax.set_title("Mean Votes")
plt.show()

